#!/usr/bin/python3
#-*- coding: utf-8 -*-
# @Time    : 2019/2/20 6:44 PM
# @Author  : way
# @Email   : wuaoyi@gmail.com
# @File    : test.py
# @Software: PyCharm

import requests,re
import time
import json
import datetime
import smtplib
import email
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email.mime.application import MIMEApplication
from email.header import Header
class Work:
    # 判断是不是工作日
    def workDay(self):
        workTime = ['17:00:00', '23:59:59']
        dayOfWeek = datetime.datetime.now().weekday()
        # dayOfWeek = datetime.today().weekday()
        beginWork = datetime.datetime.now().strftime("%Y-%m-%d") + ' ' + workTime[0]
        endWork = datetime.datetime.now().strftime("%Y-%m-%d") + ' ' + workTime[1]
        beginWorkSeconds = time.time() - time.mktime(time.strptime(beginWork, '%Y-%m-%d %H:%M:%S'))
        endWorkSeconds = time.time() - time.mktime(time.strptime(endWork, '%Y-%m-%d %H:%M:%S'))
        if (int(dayOfWeek) in range(5)) and int(beginWorkSeconds) > 0 and int(endWorkSeconds) < 0:
            return 1
        else:
            return 0
class Exchange:
    #当前日期
    ctime = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    #上海交易所的股票代码
    shStock = ['603533', '601360', '600640', '600637', '600373', '600715']
    #深圳交易所的股票代码
    szStock = ['002739', '002624', '300251', '002292', '002699', '300027', '300133', '002174', '000917', '300418', '002555', '300144', '002354', '300315', '300364', '300043', '300571', '002602', '002558', '002143', '300413']
    #上海交易所返回的列表
    shData = []
    #深圳交易所返回的列表
    szData= []
    #上海交易所内容存放
    shContent = []
    #深圳交易所数据存放
    szList = []
    #s上海交易所的静态网址
    static2_url = 'http://static.sse.com.cn'
    #深圳交易所pdf静态链接
    static_url = 'http://www.szse.cn/disclosure/listed/bulletinDetail/index.html?'
    #爬取深圳交易所的接口地址
    url3 = 'http://www.szse.cn/api/disc/announcement/annList?random=0.14432946372417632'
    #抓取深圳交易所的数据
    def shenzhen(self):
        new_content = []
        # 判断是不是工作日
        if work.workDay() == 1:
            for i in self.szStock:
                payload2 = {'seDate': [self.ctime,self.ctime], 'stock': [i],'channelCode': ["listedNotice_disc"], 'pageSize': 30, 'pageNum': 1}
                data = requests.post(self.url3, data=json.dumps(payload2), headers={'Content-Type': 'application/json'})
                data.encoding = 'utf-8'
                p_json = data.json()
                if len(p_json['data'])>0:
                    for i in p_json['data']:
                        if i['title'] not in self.szList:
                            self.szList.append(i['title'])
                            new_url = self.static_url + i['id']
                            new_content.append(i['title'] + ',' + new_url)
                            self.szData.append([i['title'],new_url])
            return self.szData
        else:
            print("非工作日或者工作日非工作时间段")

    #抓取上海交易所的内容
    def shanghai(self):
        if work.workDay() == 1:
            for i in self.shStock:
                url = 'http://www.sse.com.cn/js/common/stocks/new/' + i.strip() + '.js?_=1549031175644'
                wbdata = requests.get(url).text
                result2 = re.findall(r'bulletin_date:"' + self.ctime + '",bulletin_year:"(.*?)",bulletin_large_type:"(.*?)",bulletin_small_type:"(.*?)",bulletin_title:"(.*?)",(.*?)",',wbdata)
                if len(result2) > 0:
                    for i in result2:
                        i = list(i)
                        if i[3] not in self.shContent:
                            content = i[3]
                            self.shContent.append(i[3])
                            url = self.static2_url + i[4].replace('bulletin_file_url:"', '')
                            self.shData.append([content,url])
            return self.shData
        else:
            print("非工作日或者工作日非工作时间段")
class SendEmail:
    # 发件人地址，通过控制台创建的发件人地址
    username = 'support@ucoin.pw'
    # 发件人密码，通过控制台创建的发件人密码
    password = 'LIxing123456'
    # 自定义的回复地址
    replyto = ''
    # 收件人地址或是地址列表，支持多个收件人，最多30个
    # rcptto = ['***', '***']
    rcptto = '2868397063@qq.com'
    #发件人标题
    title = "今日快讯"
    #发件人
    poster = '三文鱼娱乐'
    # 发送邮件
    def sendemail(self,content,url):
        # 构建alternative结构
        msg = MIMEMultipart('alternative')
        msg['Subject'] = Header(self.title).encode()
        msg['From'] = '%s <%s>' % (Header(self.poster).encode(), self.username)
        msg['To'] = self.rcptto
        msg['Reply-to'] = self.replyto
        msg['Message-id'] = email.utils.make_msgid()
        msg['Date'] = email.utils.formatdate()
        # 构建alternative的text/plain部分
        textplain = MIMEText('szList', _subtype='plain', _charset='UTF-8')
        msg.attach(textplain)
        # 构建alternative的text/html部分
        texthtml = MIMEText('<a href="' + url + '">' + content + '</a>', _subtype='html', _charset='UTF-8')
        msg.attach(texthtml)
        # 发送email
        try:
            client = smtplib.SMTP()
            # SMTP普通端口为25或80
            client.connect('smtpdm.aliyun.com', 25)
            # 开启DEBUG模式
            client.set_debuglevel(0)
            client.login(self.username, self.password)
            # 发件人和认证地址必须一致
            # 备注：若想取到DATA命令返回值,可参考smtplib的sendmaili封装方法:
            #      使用SMTP.mail/SMTP.rcpt/SMTP.data方法
            client.sendmail(self.username, self.rcptto, msg.as_string())
            client.quit()
            print('email发送成功！')
        except smtplib.SMTPConnectError as e:
            print('email发送失败，连接失败:', e.smtp_code, e.smtp_error)
        except smtplib.SMTPAuthenticationError as e:
            print('email发送失败，认证错误:', e.smtp_code, e.smtp_error)
        except smtplib.SMTPSenderRefused as e:
            print('email发送失败，发件人被拒绝:', e.smtp_code, e.smtp_error)
        except smtplib.SMTPRecipientsRefused as e:
            print('email发送失败，收件人被拒绝:', e.smtp_code, e.smtp_error)
        except smtplib.SMTPDataError as e:
            print('email发送失败，数据接收拒绝:', e.smtp_code, e.smtp_error)
        except smtplib.SMTPException as e:
            print('email发送失败, ', e.message)
        except Exception as e:
            print('email发送异常, ', str(e))
if __name__ == "__main__":
    #每天爬取的深圳交易所存放列表
    arr_sz = []
    # 每天爬取的上海交易所存放列表
    arr_sh = []
    work = Work()
    sm = SendEmail()
    ex = Exchange()
    if work.workDay() == 0:
        arr_sz = []
        arr_sh = []
    resp2 = ex.shanghai()
    resp = ex.shenzhen()
    if len(resp)>0:
        for i in resp:
            if i not in arr_sz:
                arr_sz.append(i)
                sm.sendemail(i[0],i[1])
    if len(resp2) >0:
        for i in resp2:
            if i not in arr_sh:
                arr_sh.append(i)
                sm.sendemail(i[0],i[1])
    print("抓取完成")
